package com.github.tyc1210.config;

import javax.sql.DataSource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 *
 * @author tyc
 * @version 1.0
 * @date 2024-01-08 15:09:54
 */
public class DynamicContextHolder {
    /** * 多数据源执行期间 线程对应 事务用到的所有连接 */
    public static final ThreadLocal<List<CustomConnection>> MULTI_TRAN_CONNECTION = ThreadLocal.withInitial(()->new ArrayList<>());
    /** * 保存所有数据源 */
    private static final Map<String, DataSource> DATA_SOURCE_MAP  = new ConcurrentHashMap<>();
    /** 记录当前线程对应的数据源 Key */
    private static final ThreadLocal<String> CONTEXT_HOLDER = ThreadLocal.withInitial(()->"");

    public static void putDataSource(String key,DataSource dataSource){
        DATA_SOURCE_MAP.put(key,dataSource);
    }

    /**
     * 获取当前线程的指定数据源
     */
    public static DataSource getThreadDataSources(String key){
       return DATA_SOURCE_MAP.get(key);
    }


    /**
     * 获得当前线程数据源 key
     */
    public static String getKey() {
        return CONTEXT_HOLDER.get();
    }

    /**
     * 设置当前线程数据源 key
     */
    public static void setKey(String key) {
        CONTEXT_HOLDER.set(key);
    }

    public static void remove(){
        CONTEXT_HOLDER.remove();
    }
}
